//
//  UserAccount.swift
//  SwiftWB
//
//  Created by 钟清 on 17/3/30.
//  Copyright © 2017年 Zhong Qing. All rights reserved.
//

import UIKit

class UserAccount: NSObject,NSCoding {
    /* 令牌 */
    var access_token: String?
    /* 服务器返回令牌过期时间：s */
    var expires_in: Int = 0 { // 实际返回数据为Int，官方文档为String
        didSet {
            expires_date = NSDate(timeIntervalSinceNow: NSTimeInterval(expires_in))
        }
    }
    /* 自定义真正过期时间 */
    var expires_date: NSDate?
    /* 用户ID */
    var uid: String?
    /* 用户头像地址（大图），180×180像素 */
    var avatar_large: String?
    /* 用户昵称 */
    var screen_name: String?
    
    // MARK: - Life
    init(dict: [String : AnyObject]) {
        super.init()
        self.setValuesForKeysWithDictionary(dict)
    }

    // 没有对应的Key时候调用
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    // FIXME: - 快速调试
    override var description: String {
        let property = ["access_token","expires_in","uid","expires_date"]
        let dict = dictionaryWithValuesForKeys(property)
        return "\(dict)"
    }
    
    // MARK: - 外部控制方法
    // 归档自定义模型
    static var account: UserAccount?
    /* 文件路径 */
    static var filePath: String = "useraccount.plist".cachesDir()
    
    func saveAccount() -> Bool {
        ZQLog(UserAccount.filePath)
        return NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.filePath)
    }
    // 解归档模型
    class func  loadUserAccount() -> UserAccount? {
        // TODO: -此处是否需要判断令牌过期？
        if UserAccount.account != nil {
            ZQLog("account已经加载过了")
            ZQLog(UserAccount.filePath)
            return UserAccount.account
        }
        ZQLog("account没有被加载过")
        guard let account = NSKeyedUnarchiver.unarchiveObjectWithFile(UserAccount.filePath) as? UserAccount else {
            return UserAccount.account
        }
        /* 判断令牌是否过期 */
        guard let date = account.expires_date where date.compare(NSDate()) != NSComparisonResult.OrderedAscending else {
            ZQLog("令牌已经过期了")
            return nil
        }

        UserAccount.account = account
        return UserAccount.account
    }
    
    /*  获取用户信息 */
    func loadUserInfo(finished: (account: UserAccount?, error: NSError?) -> ()) {
        
        /* 断言：使用需有值 */
        assert(access_token != nil, "使用该方法必须先授权")
        let path = "2/users/show.json"
        let parameters = ["access_token" : access_token!, "uid" : uid!];
        NetworkTools.shareInstance.GET(path, parameters: parameters, success: { (task, objc) in
            ZQLog(objc)
            let tempObjc = objc as! [String : AnyObject]
            self.avatar_large = tempObjc["avatar_large"] as? String
            self.screen_name = tempObjc["screen_name"] as? String
            
            finished(account: self, error: nil)
            
            }) { (task, error) in
                finished(account: nil,error: error)
        }
    }
    
    // 判断用户是否登录过
    class func isLogin() -> Bool {
        return UserAccount.loadUserAccount() != nil
    }
    
    // MARK: - NSCoding
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeInteger(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
    }
    required init?(coder aDecoder: NSCoder) {
        self.access_token = aDecoder.decodeObjectForKey("access_token") as? String
        self.expires_in = aDecoder.decodeIntegerForKey("expires_in") as Int
        self.uid = aDecoder.decodeObjectForKey("uid") as? String
        self.expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
        self.avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        self.screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
    }
}
